package com.example.smartall.adapter;

import android.content.Context;
import android.text.Layout;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

import java.util.List;

/**
 * @author abbas
 * @brief 万能适配器 偶然百度看到 自己实现觉得困难重重 笑死
 * @date 2022-01-23
 */
public abstract class PervasiveAdapter<T> extends BaseAdapter {

    private List<T> mData;

    public PervasiveAdapter(List<T> data) {
        mData = data;
    }

    public void setData(List<T> data){
        mData = data;
        notifyDataSetChanged();
    }

    public List<T> getData(){
        return mData;
    }

    @Override
    public int getCount() {
        return mData == null ? 0 : mData.size();
    }

    @Override
    public T getItem(int position) {
        return mData.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder = ViewHolder.newsInstance(convertView, parent.getContext(), getLayoutId());
        setUI(holder, position, parent.getContext());
        return holder.getConverView();
    }

    protected abstract void setUI(ViewHolder holder, int position, Context context);

    protected abstract int getLayoutId();

    public static class ViewHolder {
        /**
         * 保存所有itemview的集合
         */
        private SparseArray<View> mViews;

        private View mConvertView;

        private ViewHolder(Context context, int layoutId) {
            mConvertView = View.inflate(context, layoutId, null);
            mConvertView.setTag(this);
            mViews = new SparseArray<>();
        }

        public static ViewHolder newsInstance(View convertView, Context context, int layoutId) {
            if (convertView == null) {
                return new ViewHolder(context, layoutId);
            } else {
                return (ViewHolder) convertView.getTag();
            }
        }

        /**
         * 获取根view
         *
         * @return
         * @author 漆可
         * @date 2016-6-28 下午3:29:21
         */
        public View getConverView() {
            return mConvertView;
        }

        /**
         * 获取节点view
         *
         * @param id
         * @return
         * @author 漆可
         * @date 2016-6-28 下午4:24:26
         */
        @SuppressWarnings("unchecked")
        public <T extends View> T getItemView(int id) {
            View view = mViews.get(id);
            if (view == null) {
                view = mConvertView.findViewById(id);
                mViews.append(id, view);
            }
            return (T) view;
        }
    }
}

